<?php

// 登录

namespace app\shop\controller;

use think\Db;
use think\Url;
use think\Cache;
use think\Request;
use think\Session;
use think\Controller;
use app\shop\model\Member as MemberModel;
use app\shop\model\InformationType as InformationTypeModel;
use app\shop\model\MemberShoppingCart as MemberShoppingCartModel;

class Login extends Controller
{

    /**
     * 登录页面
     * @param Request $request
     * @param MemberModel $member
     * @param InformationTypeModel $informationType
     * @return array|mixed
     */
    public function index(Request $request, MemberModel $member, InformationTypeModel $informationType)
    {
        if ($request->isPost()) {
            // 获取数据
            $data = $request->param();

            if (empty($data['username']) || empty($data['password'])) return ['code' => 200, 'message' => '账号和密码不能为空！'];

            $find = $member->where(['username' => $data['username'], 'password' => mcs($data['password'])])->find();

            if ($find) {
                // 判断购物车
                $cart = (new MemberShoppingCartModel())->where('member_id', $find['id'])->count();
                Session::set('shop_cart', $cart);
                Session::set('member_id', $find['id']);
                Session::set('member_name', $find['nickname']);
                Session::set('member_avatar', $find['avatar']);

                return ['code' => 200];
            }

            return ['code' => 402, 'message' => '账号和密码不匹配！'];
        }

        // 底部导航
        $foot = $informationType::all();
        $back_ground = Db::name('ad')->where('parenTid', 10)->value('picUrl');


        return $this->fetch('index', [
            'mate_title' => '欢迎登录',
            'mate_head'  => '登录',
            'data'       => $back_ground,
            'foot'       => get_cate($foot, 57),
        ]);
    }


    /**
     * 会员注册
     * @param Request $request
     * @param MemberModel $member
     * @return array
     */
    public function register(Request $request, MemberModel $member)
    {
        if ($request->isPost()) {
            // 获取数据
            $data = $request->param();

            //获取验证码
            $code = Cache::get('pc_register' . $data['username']);
            if ($code != $data['code']) return ['code' => 402, 'message' => '验证码错误！'];

            // 判断邀请人ID是否存在
            if ($data['referrals_id']) if (empty($member->where(['id' => $data['referrals_id']])->find())) return ['code' => 402, 'message' => '您输入的邀请人ID不存在！'];


            $operation = $member->registerMember();

            if ($operation == true) {

                return ['code' => 200];
            } else {

                return ['code' => 400];
            }

        }

        $back_ground = Db::name('ad')->where('parenTid', 10)->value('picUrl');

        return $this->fetch('', [
            'data' => $back_ground,
        ]);
    }

    public function personal()
    {
        $user_id = Session::get('member_id');

        $member = new MemberModel();

        if (Request::instance()->isPost()) {
            // 获取数据
            $data = Request::instance()->param();
            $data['password'] = mcs($data['password']);
            //获取验证码
            $code = Cache::get('pc_weixin' . $data['username']);
            if ($code != $data['code']) return ['code' => 402, 'message' => '验证码错误！'];

            // 判断邀请人ID是否存在
            if (!empty($data['referrals_id'])) if (empty($member->where(['id' => $data['referrals_id']])->find())) return ['code' => 402, 'message' => '您输入的邀请人ID不存在！'];
            if (empty($data['referrals_id'])) $data['referrals_id'] = 0;
            $member->distribution($data['referrals_id'],$user_id);
            $operation = $member->allowField(true)->save(['username'=>$data['username'],'password'=>$data['password']],['id'=>$user_id]);

            if ($operation) {
                return ['code' => 200];
            }else{
                return ['code' => 400];
            }

        }

        $back_ground = Db::name('ad')->where('parenTid', 10)->value('picUrl');



        return $this->fetch('',[
            'data' => $back_ground,
        ]);
    }


    /**
     * 忘记密码
     * @param Request $request
     * @param MemberModel $member
     * @return array|mixed
     */
    public function forget(Request $request, MemberModel $member)
    {

        if ($request->isPost()) {
            $data = $request->param();
            // 验证手机号是否存在
            $find = $member->where(['username' => $data['username']])->find();

            if ($find) {
                Session::set('forget_mobile', $data['username']);

                return ['code' => 200];
            }
            return ['code' => 402, 'message' => '该用户不存在'];
        }


        return $this->fetch('', [
            'mate_head' => '忘记密码',
        ]);
    }


    /**
     * 发送验证码
     * @param Request $request
     * @return array
     */
    public function getVerif(Request $request)
    {
        if ($request->isPost()) {
            // 获取参数
            $tel = $request->param('tel');
            $act = $request->param('act');
            //验证码随机数
            $code = mt_rand(100000, 999999);
            $content = "您的验证码是" . $code;
            // 验证码状态
            $result = sendSMS($tel, $content);

            //发送验证码
            if ($result > 0) {
                Cache::set($act . $tel, $code, 120);
                return ['code' => 200, 'message' => $code];
            }
            return ['code' => 401, 'message' => '网络繁忙'];

        }
    }


    /**
     * 验证手机号唯一性
     * @param Request $request
     * @param MemberModel $member
     * @return array
     */
    public function bind_phone(Request $request, MemberModel $member)
    {

        if ($request->isPost()) {
            //检测新绑定手机号的唯一性
            $new_bind = $request->post('tel');
            $id = $member->where('username', $new_bind)->value('id');
            return !$id ? ['code' => 200] : ['code' => 0, 'message' => '输入的手机号已存在,请更换!'];
        }

    }


    /**
     * 账户是否存在
     * @param Request $request
     * @param MemberModel $member
     * @return array
     */
    public function verify_phone(Request $request, MemberModel $member)
    {
        // 获取参数
        $data = $request->param('tel');
        // 验证手机号是否存在
        $find = $member->where(['username' => $data])->find();

        if ($find) {
            return ['code' => 200];
        }
        return ['code' => 402, 'message' => '该用户不存在'];

    }

    /**
     * 生成图片验证码
     */
    //vCode 字符数目，字体大小，图片宽度、高度
    public function vCode($num = 4, $size = 20, $width = 0, $height = 0)
    {


        !$width && $width = $num * $size * 4 / 5 + 15;
        !$height && $height = $size + 10;

        //设置验证码字符集合
        $str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW";
        //保存获取的验证码
        $code = '';

        //随机选取字符
        for ($i = 0; $i < $num; $i++) {
            $code .= $str[mt_rand(0, strlen($str) - 1)];
        }

        //创建验证码画布
        $im = imagecreatetruecolor($width, $height);

        //背景色
        $back_color = imagecolorallocate($im, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));

        //文本色
        $text_color = imagecolorallocate($im, mt_rand(100, 255), mt_rand(100, 255), mt_rand(100, 255));

        imagefilledrectangle($im, 0, 0, $width, $height, $back_color);


        // 画干扰线
        for ($i = 0; $i < 5; $i++) {
            $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
            imagearc($im, mt_rand(-$width, $width), mt_rand(-$height, $height), mt_rand(30, $width * 2), mt_rand(20, $height * 2), mt_rand(0, 360), mt_rand(0, 360), $font_color);
        }

        // 画干扰点
        for ($i = 0; $i < 50; $i++) {
            $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
            imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $font_color);
        }

        //随机旋转角度数组
        $array = array(5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5);

        // 输出验证码
        // imagefttext(image, size, angle, x, y, color, fontfile, text)
        @imagefttext($im, $size, array_rand($array), 12, $size + 6, $text_color, 'c:\WINDOWS\Fonts\simsun.ttc', $code);

        $_SESSION["PictureCode"] = $code;


        //no-cache在每次请求时都会访问服务器
        //max-age在请求1s后再次请求会再次访问服务器，must-revalidate则第一发送请求会访问服务器，之后不会再访问服务器
        // header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate");
        header("Cache-Control: no-cache");
        header("Content-type: image/png;charset=gb2312");
        //将图片转化为png格式
        imagepng($im);
        imagedestroy($im);
    }


    /**
     * 判断验证码
     * @param Request $request
     * @param MemberModel $member
     * @return array
     */
    public function verif(Request $request, MemberModel $member)
    {

        if ($request->isPost()) {
            // 获取参数
            $data = $request->param();

            //获取验证码
            $code = Cache::get('pc_forget' . Session::get('forget_mobile'));
            if ($code != $data['code']) {
                return ['code' => 402, 'message' => '验证码错误'];
            } else {
                return ['code' => 200, 'message' => '验证码正确'];
            }

        }


        return $this->fetch('', [
            'mate_head' => '找回密码',
            'username'  => Session::get('forget_mobile')
        ]);
    }


    public function edit_password(Request $request, MemberModel $member)
    {
        if ($request->isPost()) {
            $data = $request->param();

            if ($data['pwd'] != $data['upwd']) return ['code' => 402, 'message' => '两次密码不一致！'];


            $new_password = md5(md5($data['pwd']));
            $operation = $member->where('username', Session::get('forget_mobile'))->update(['password' => $new_password]);

            if ($operation) {
                return ['code' => 200];
            }
            return ['code' => 402, 'message' => '网络繁忙，请稍后再试！'];
        }


        return $this->fetch('', [
            'mate_head' => '找回密码',

        ]);
    }



    /**
     * 注销登录
     */
    public function logout()
    {
        Session::delete('member_id');
        Session::delete('member_name');
        Session::delete('member_avatar');
        Session::delete('shop_cart');
        $this->redirect(Url::build('shop/index/index'));
    }
}